﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Ymt.Repository;
using YmtRpc.Domain;
using YmtRpc.Domain.Enum;

namespace YmtRpc.Domain
{

    /// <summary>
    /// RPC服务依赖配置的仓储类
    /// </summary>
    public class ServiceconfigRepository : MySQLRepository<SeviceConfig>, IServiceconfigRepository
    {
        public ServiceconfigRepository()
            : base()
        {

        }

        /// <summary>
        /// 获取RPC服务依赖配置列表
        /// </summary>
        /// <returns></returns>
        public List<SeviceConfig> GetList(DependencyRelationEnum dependencyRelation, string appId)
        {
            List<SeviceConfig> list = new List<SeviceConfig>();
            string sql = "select * from serviceconfig";
            ParametersWrapper par = new ParametersWrapper();

            if (dependencyRelation == DependencyRelationEnum.Dependent)
            {
                sql += " WHERE ConsumerAppId = @ConsumerAppId";
                par.Add("ConsumerAppId", appId);
            }
            else
            {
                sql += " WHERE ProviderAppId = @ProviderAppId";
                par.Add("ProviderAppId", appId);
            }

            var result = Query(sql, par.Build());
            if (result != null && result.Any())
            {
                list = result.ToList();
            }

            return list;
        }

        /// <summary>
        /// 获取应用程序列表
        /// </summary>
        /// <returns></returns>
        public List<string> GetAppList(DependencyRelationEnum dependencyRelation)
        {
            List<string> list = new List<string>();
            string sql = string.Empty;
            ParametersWrapper par = new ParametersWrapper();

            if(dependencyRelation == DependencyRelationEnum.Dependent)
            {
                sql = "select DISTINCT ConsumerAppId from serviceconfig";

                var result = Query(sql, par.Build());
                if (result != null && result.Any())
                {
                    list = result.Select(r => r.ConsumerAppId).ToList();
                }
            }
            else
            {
                sql = "select DISTINCT ProviderAppId from serviceconfig";

                var result = Query(sql, par.Build());
                if (result != null && result.Any())
                {
                    list = result.Select(r => r.ProviderAppId).ToList();
                }
            }

            return list;
        }
    }
}
